package com.trinhrae.shooting.moduleGeneral.service;

import com.alibaba.fastjson.JSONObject;
import com.trinhrae.shooting.entity.MailRequest;
import freemarker.template.TemplateException;
import netscape.javascript.JSObject;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.io.IOException;
import java.util.List;

/**
 * @Author: TrinhRae
 * @Package: com.trinhrae.shooting.moduleGeneral.service
 * @Project: shooting
 * @Date: 2025/9/17 17:31
 */
@Service
public class KafkaConsumerService {

    private final EmailService emailService;

    public KafkaConsumerService(EmailService emailService) {
        this.emailService = emailService;
    }

    @KafkaListener(topics = "send-verify-code", groupId = "test-group")
    public void sendVerifyCode(List<String> message, Acknowledgment acknowledgment) throws MessagingException, TemplateException, IOException {
        try {
            for (String infoContent : message) {
                JSONObject infoJson = JSONObject.parseObject(infoContent);
                String email = infoJson.getString("email");
                String code = infoJson.getString("code");
                // 构建邮件；发送验证码
                MailRequest mailRequest = new MailRequest();
                mailRequest.setSendTo(email);
                mailRequest.setSubject("验证码");
                mailRequest.setText(code);
                emailService.sendHtmlMail(mailRequest);
            }
        } finally {
            acknowledgment.acknowledge();
        }
    }
}
